package logic

import (
	"context"
	"fmt"
	"math/rand"
	"time"
	"wechat/models/redisInit"
	"wechat/userrpc/internal/svc"
	"wechat/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *userrpc.SendSmsRequest) (*userrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	get := redisInit.Client.Get("sendSmsMinute" + in.Mobile)

	if get.Val() >= "3" {
		return nil, fmt.Errorf("您已经发送三次了  五分钟内不允许发送")
	}

	code := rand.Intn(9000) + 1000

	//sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	//if err != nil {
	//	return nil, err
	//}
	//
	//if *sms.Body.Code != "OK" {
	//	return nil, fmt.Errorf(*sms.Body.Message)
	//}

	redisInit.Client.Set("sendSms"+in.Source+in.Mobile, code, time.Minute*3)

	////每五分钟只能发一次
	//redisInit.Client.Set(key, "1", time.Minute*5)

	//每五分钟只能发三次???
	incr := redisInit.Client.Incr("sendSmsMinute" + in.Mobile)

	//我发送三次之后我限制其五分钟不能发送
	if incr.Val() >= 3 {
		redisInit.Client.Expire("sendSmsMinute"+in.Mobile, time.Minute*5)
	}

	return &userrpc.SendSmsResponse{}, nil
}
